<template>
  <div class="app-container">
    <el-dialog title="设置分类" :visible.sync="settingVisible" width="1000px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
      <el-form ref="classForm" :model="classForm" label-width="100px" :inline="true">
        <el-form-item label="分类名称" prop="label" :rules="{ required: true, message: '请输入分类名称', trigger: 'blur' }">
          <el-input v-model.trim="classForm.label" style="width:220px" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="addDic">添加</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="dicListLoading" :data="diclist" highlight-current-row style="width: 100%;" border class="settingDicTable">
        <!-- <el-table-column prop="dictCode" label="编号" width="100" /> -->
        <el-table-column prop="dictText" label="名称" />
        <!-- <el-table-column prop="dataCreateDatetime" label="创建日期" width="120" /> -->
        <!-- <el-table-column prop="amount" label="文章数量(已发布)" width="160" /> -->
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            {{ scope.row.dataDeleted?'停用':'启用' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-popconfirm v-if="!scope.row.dataDeleted" title="确定停用该分类吗？" @onConfirm="stopDic(scope.row.dictCode)">
              <el-button slot="reference" type="danger" icon="el-icon-warning" :loading="stopDicLoading" size="mini">停用</el-button>
            </el-popconfirm>
            <el-popconfirm v-if="scope.row.dataDeleted" title="确定启用该分类吗？" @onConfirm="startDic(scope.row.dictCode)">
              <el-button slot="reference" type="success" icon="el-icon-success" :loading="startDicLoading" size="mini">启用</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      :title="dialogtitle"
      :visible.sync="dialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <dynamicEdit :infoid="id" :read-only="readOnly" :timestamp="timestamp" @dialogHide="dialogHide($event)" />
    </el-dialog>

    <div class="filter-container">
      <!-- <el-select v-model="listQuery.classCode" placeholder="请选择车辆类型" clearable style="margin-left: 10px;width: 200px" class="filter-item">
        <el-option label="全部" value="" />
        <el-option v-for="(it,index) in classList" :key="index" :label="it.label" :value="it.value" />
      </el-select> -->
      <el-input v-model="listQuery.title" placeholder="请输入字段代号" style="width: 200px;margin-left: 10px;" class="filter-item" />
      <!-- <el-date-picker v-model="listQuery.publishTime" placeholder="请选择日期" style="width: 200px;margin-left: 10px;" value-format="yyyy-MM-dd" class="filter-item" /> -->
      <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilter">
        搜索
      </el-button>

      <!-- <el-button v-if="roleEdit" style="margin-left: 10px;float:right" class="filter-item" type="primary" icon="el-icon-download" @click="showDic">
        类别管理
      </el-button> -->
      <el-button class="filter-item" style="margin-left: 10px;float:right" type="success" icon="el-icon-edit" @click="addnew">
        新建
      </el-button>
    </div>

    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />

      <el-table-column width="120px" prop="class_code" label="车辆类型" align="center" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.classText }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="id" label="字段代号" width="120" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="300px" prop="title" label="字段名称" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>

      <el-table-column label="状态" prop="user_enabled" width="100" align="center" sortable="custom">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.enabled" type="success" effect="dark" style="cursor:pointer" title="停用" @click="setState(scope.row.id,false,scope.row.realName)">正常</el-tag>
          <el-tag v-else type="info" effect="dark" style="cursor:pointer" title="启用" @click="setState(scope.row.id,true,scope.row.realName)">停用</el-tag>
        </template>
      </el-table-column>
      <!--
      <el-table-column label="访问次数" prop="read_num" width="110" align="center" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.readNum }}
        </template>
      </el-table-column>
      <el-table-column label="置顶" prop="is_top" width="90" align="center" sortable="custom">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isTop" style="cursor:pointer !important" effect="dark" title="将此信息取消置顶" @click="isTop(scope.row.id,0,scope.row.title)">是</el-tag>
          <el-tag v-else type="info" effect="dark" style="cursor:pointer !important" title="将此信息设为置顶" @click="isTop(scope.row.id,1,scope.row.title)">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="state" width="90" align="center" sortable="custom">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state" type="success" effect="dark" style="cursor:pointer" title="取消发布此信息" @click="setState(scope.row.id,0,scope.row.title)">已发布</el-tag>
          <el-tag v-else type="info" effect="dark" style="cursor:pointer" title="发布此信息" @click="setState(scope.row.id,1,scope.row.title)">未发布</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-search" @click="detail(scope.row.id)">
            查看
          </el-button>
          <el-button v-if="roleEdit" type="primary" size="small" icon="el-icon-edit" @click="edit(scope.row.id)">
            编辑
          </el-button>
          <!-- <el-popconfirm v-if="roleEdit" title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="deleteData(scope.row.id)">
            <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
          </el-popconfirm> -->
          <!-- <el-button v-if="selection" type="warning" size="small" icon="el-icon-success" style="margin-left:10px;" @click="selectInfo(scope.row)">
            选取
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
// import { fetchList } from '@/api/article'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import dynamicEdit from './edit'

export default {
  name: 'ArticleList',
  components: { Pagination, dynamicEdit },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  props: {
    isEdit: {
      type: Boolean,
      default: true
    },
    isSelection: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleEdit: false,
      rolePublisher: false,
      selection: false,
      dicListLoading: false,
      stopDicLoading: false,
      startDicLoading: false,
      submitLoading: false,
      classList: [],
      classForm: {
        parentClass: 14,
        label: ''
      },
      diclist: [],
      settingVisible: false,
      item: {},
      dialogtitle: '新增',
      dialogVisible: false,
      readOnly: false,
      timestamp: false,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      Sortkey: '',
      Isace: '',
      multipleSelection: [],
      id: ''
    }
  },
  watch: {
    isEdit: {
      handler(val) {
        console.log('isEdit:' + val)
        this.roleEdit = val
      },
      immediate: true
    },
    isSelection: {
      handler(val) {
        console.log('isSelection:' + val)
        this.selection = val
      },
      immediate: true
    }
  },
  created() {
    this.getList()
    this.getClass()
    // this.getMyRole()
  },
  mounted() {
    if (JSON.parse(localStorage.getItem('user')).auths.includes('AUTH_close')) {
      this.roleEdit = true
    } else {
      this.roleEdit = false
    }
  },
  methods: {
    replaceHtml(str) {
      var re = new RegExp('<[^<>]+>', 'g')
      var text1 = str.replace(re, '')
      return text1
    },
    getMyRole() {
      this.$http
        .get('/api/sysAuth/getCurrentAuthByUser')
        .then(response => {
          if (response.data.success === true) {
            const myActions = response.data.result
            this.checkRole(myActions, 5)
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    checkRole(actions, menuid) {
      console.log('checkRole')
      if (actions.filter(item => item.sysMenuId === menuid && item.actionType === '0301').length > 0) {
        this.roleEdit = true
      } else {
        this.roleEdit = false
      }
      if (actions.filter(item => item.sysMenuId === menuid && item.actionType === '0302').length > 0) {
        this.rolePublisher = true
      } else {
        this.rolePublisher = false
      }
      this.roleEdit = true
      this.rolePublisher = true
    },
    selectInfo(data) {
      this.$emit('selected', data)
    },
    setState(id, state, title) {
      if (this.rolePublisher && !this.selection) {
        const stateText = state ? ' 发布 ' : ' 取消发布 '
        this.$confirm('确定要' + stateText + ' “' + title + '” 这信息吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http
            .post('/api/busInformation/save', { id: id, state: state })
            .then(response => {
              if (response.data.success === true) {
                this.$message({
                  message: stateText + '成功',
                  type: 'success'
                })
                this.getList()
              } else {
                console.log(stateText + '失败:' + response.data.message)
                this.$message({
                  message: stateText + '失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              console.log(error)
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已放弃' + stateText + '操作'
          })
        })
      }
    },
    isTop(id, state, title) {
      if (this.rolePublisher && !this.selection) {
        const stateText = state ? ' 置顶 ' : ' 取消置顶 '
        this.$confirm('确定要' + stateText + ' “' + title + '” 这信息吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http
            .post('/api/busInformation/save', { id: id, isTop: state })
            .then(response => {
              if (response.data.success === true) {
                this.$message({
                  message: stateText + '成功',
                  type: 'success'
                })
                this.getList()
              } else {
                console.log(stateText + '失败:' + response.data.message)
                this.$message({
                  message: stateText + '失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              console.log(error)
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已放弃' + stateText + '操作'
          })
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteData(id) {
      let ids = []
      if (id) {
        ids = [id]
      } else {
        ids = this.multipleSelection.map(item => item.id)
      }
      if (ids.length > 0) {
        this.$http
          .post('/api/knowledge/remove', { ids: ids })
          .then(response => {
            if (response.data.success === true) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getList()
            } else {
              console.log('删除失败:' + response.data.message)
              this.$message({
                message: '删除失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    sortChange(column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = 'asc'
      } else {
        this.Isace = 'desc'
      }
      this.getList()
    },
    getClass() {
      const code = '04'
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=' + code)
        .then(response => {
          if (response.data.success === true) {
            this.classList = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    stopDic(code) {
      this.stopDicLoading = true
      this.$http
        .get('/api/sysDict/disableByCode?dictCode=' + code)
        .then(response => {
          this.stopDicLoading = false
          if (response.data.success === true) {
            this.getDic()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          } else {
            console.log('操作失败:' + response.data.message)
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.stopDicLoading = false
        })
    },
    startDic(code) {
      this.startDicLoading = true
      this.$http
        .get('/api/sysDict/enableByCode?dictCode=' + code)
        .then(response => {
          this.startDicLoading = false
          if (response.data.success === true) {
            this.getDic()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          } else {
            console.log('操作失败:' + response.data.message)
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.startDicLoading = false
        })
    },
    showDic() {
      this.settingVisible = true
      this.getDic()
    },
    getDic() {
      this.dicListLoading = true
      this.$http
        .get('/api/busInformation/getDictList')
        .then(response => {
          this.dicListLoading = false
          if (response.data.success === true) {
            this.diclist = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.dicListLoading = false
        })
    },
    addDic() {
      this.$refs.classForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          const para = {
            dictText: this.classForm.label,
            parentCode: '04'
          }
          this.$http
            .post('/api/sysDict/create', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.classForm.label = ''
                this.getDic()
              } else {
                console.log('添加失败:' + response.data.message)
                this.$message({
                  message: '添加失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              console.log(error)
              this.submitLoading = false
            })
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    addnew() {
      this.id = 0
      this.readOnly = false
      this.dialogtitle = '新增'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    edit(id) {
      this.id = id
      this.readOnly = false
      this.dialogtitle = '编辑'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    detail(id) {
      this.id = id
      this.readOnly = true
      this.dialogtitle = '查看'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    dialogHide(flag) {
      this.dialogVisible = false
      this.getList()
    },
    getList() {
      const para = {
        classCode: this.listQuery.classCode,
        orderField: this.Sortkey,
        orderType: this.Isace,
        pageNum: this.listQuery.page,
        pageSize: this.listQuery.limit,
        key: this.listQuery.title
      }
      this.listLoading = true
      this.$http
        .post('/api/knowledge/queryPage', para)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            this.list = response.data.result.records
            this.total = response.data.result.total
            if (response.data.result.current > response.data.result.pages && response.data.result.pages !== 0) {
              this.listQuery.page = response.data.result.pages
              this.getList()
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.listLoading = false
        })
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //   this.listLoading = false
      // })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
